//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////

#if Gdmp || Gnuf
using Glodon.Gdmp.DB;
#elif Gap
using Glodon.Gap.DB;
#endif
using Glodon.Lookup.Core.Contracts;
using Glodon.Lookup.Core.ModelBase;
using Glodon.Lookup.Lookup.Core;
using Glodon.Lookup.Models;
using Glodon.Lookup.Services.Enums;
using Glodon.Lookup.ViewModels.Contracts;
using Glodon.Lookup.Models.Descriptors;

using Wpf.Ui.Common;
using Wpf.Ui.Contracts;
using Wpf.Ui.Controls;

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

using System.Windows.Input;
using System.Windows.Threading;

namespace Glodon.Lookup.ViewModels.Pages
{
    public abstract partial class SnoopViewModelBase : ObservableObject, ISnoopViewModel
    {
        private readonly ISnackbarService _snackbarService;

        [ObservableProperty] private bool _supressToggleCommand;
        [ObservableProperty] private bool supressTreeSelectedChangedCommand;

        protected SnoopViewModelBase(ISnackbarService snackbarService)
        {
            _snackbarService = snackbarService;
        }

        public ICommand ExitCommand { get; set; }

        public event EventHandler TreeSourceChanged;
        public event EventHandler SearchResultsChanged;

        public virtual async void Snoop(SnoopableObject snoopableObject)
        {

        }
        public virtual async Task CollectMembers(bool useCached)
        {

        }
        protected virtual void OnTreeSelectedChanged(SnoopableObject newObj) { }
        public abstract Task Snoop(DataTabType tab);

        public void Navigate(Descriptor selectedItem)
        {
            if (selectedItem == null)
            {
                return;
            }
            if (!(selectedItem.Value.Descriptor is IDescriptorCollector) ||
                selectedItem.Value.Descriptor is IDescriptorEnumerator { IsEmpty: true })
                return;
            Snoop(selectedItem.Value);
        }

        [RelayCommand]
        private async Task FetchMembersAsync()
        {
            await CollectMembers(true);
        }

        [RelayCommand]
        private async Task RefreshMembersAsync()
        {
            await CollectMembers(false);
        }
        [RelayCommand]
        private void ShowElement(object parameter)
        {
            if (parameter == null)
            {
                return;
            }
            if (parameter is SnoopableObject sn)
            {
                if (GlodonAPI.UiDocument is null) return;
                if (sn.Object is Document doc || sn.Object is ModelView mdv)
                {
                    //todo 缩放匹配
                    return;
                }
                if (sn.Object is not Element)
                {
                    _snackbarService.ShowAsync("提示", "非图元无法居中显示", SymbolRegular.Warning16, ControlAppearance.Caution);
                    return;
                }
                Element? element = sn.Object as Element;
                if ((sn.Descriptor as ElementDescriptor)!.CanShow)
                {
                    Dispatcher.CurrentDispatcher.Invoke(() =>
                    {
                        try
                        {
                            using (Transaction tran = new(GlodonAPI.Document, "scale match"))
                            {
                                tran.Start();
                                try
                                {
                                    GlodonAPI.UiDocument.ShowElement(element!.Id);
                                    GlodonAPI.UiDocument.Selection.SetElementIds(new List<ElementId>() { element.Id });
                                    GlodonAPI.UiDocument.CurrentUIView.Refresh();
                                    tran.Commit();
                                }
                                catch (Exception)
                                {
                                    if (tran.HasStarted())
                                    {
                                        tran.RollBack();
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            _snackbarService.ShowAsync("居中显示失败", e.Message, SymbolRegular.ErrorCircle16, ControlAppearance.Danger);
                        }
                    });
                }
                else
                {
                    _snackbarService.Show("提示", $"该元素无法居中显示", SymbolRegular.Warning16, ControlAppearance.Caution);
                }
            }

        }
        [RelayCommand]
        private async void TreeSelectedChanged(object selectedValue)
        {
            try
            {
                var newObject = selectedValue as SnoopableObject;
                if (newObject == null)
                {
                    return;
                }
                await FetchMembersAsync();
                OnTreeSelectedChanged(newObject);
            }
            catch (Exception e)
            {
                SnowException("树选择改变处理异常", e.Message + e.StackTrace);
            }
        }

        protected void SnowException(string title, string message)
        {
            _snackbarService.Show(title, message, SymbolRegular.ErrorCircle24, ControlAppearance.Danger);
        }

    }
}
